package com.jcp.controller;

import java.io.IOException;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import com.google.gson.Gson;
import com.jcp.daoimp.LateAndOvertimeUsersDaoImp;
import com.jcp.entity.AddressBook;
import com.jcp.entity.Attences;
import com.jcp.entity.LateAndOvertimeUsers;
import com.jcp.entity.Notices;
import com.jcp.entity.OverTime;
import com.jcp.entity.Requests;
import com.jcp.entity.UserMessage;
import com.jcp.entity.Users;
import com.jcp.entity.UsersLogin;
import com.jcp.service.AttencesService;
import com.jcp.service.LateAndOvertimeUsersService;
import com.jcp.serviceimp.AttencesServiceImp;
import com.jcp.serviceimp.DepartmentsServiceImp;
import com.jcp.serviceimp.FilesServiceImp;
import com.jcp.serviceimp.LateAndOvertimeUsersServiceImp;
import com.jcp.serviceimp.NoticesServiceImp;
import com.jcp.serviceimp.RequestsServiceImp;
import com.jcp.serviceimp.UserServiceImp;
import com.jcp.util.PageData;

/**
 * Servlet implementation class StaffServlet
 */
@WebServlet(name = "min.do", urlPatterns = { "/min.do" })
public class MinisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	FilesServiceImp filesServiceImp = new FilesServiceImp();
	AttencesServiceImp attencesServiceImp = new AttencesServiceImp();
	NoticesServiceImp noticesServiceImp = new NoticesServiceImp();
	UserServiceImp userServiceImp = new UserServiceImp();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MinisterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*
		 * //2设置预期响应的类型为application/json response.setContentType("application/json");
		 * 
		 * //3创建printWriter对象 PrintWriter out = response.getWriter();
		 */

		request.setCharacterEncoding("utf-8");
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		String op = "";
		// 获取页面传输的op值
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		// 查询通讯录
		if (op.equals("adb")) {
			// 操作针对分页的操作
			// 三个参数 从页面来的
			int page = 1;
			int pageSize = 10;
			String strLike = "";
			if (request.getParameter("page") != null) {
				page = Integer.valueOf(request.getParameter("page"));
			}

			if (request.getParameter("pageSize") != null) {
				pageSize = Integer.valueOf(request.getParameter("pageSize"));
			}
			if (request.getParameter("strLike") != null) {
				strLike = request.getParameter("strLike");
			}
			// 获取分页的通讯录数据
			PageData<AddressBook> pageData = filesServiceImp.selUserPhoneByPage(page, pageSize, strLike);
			// 将分页后得到的pagedata发送到页面
			// LayuiData<AddressBook> layuiData = new LayuiData<>(0, "",
			// pageData.getTotalCount(), pageData.getData());
			System.out.println(pageData.getData());

			// String returnValue=new Gson().toJson(layuiData);
			/*
			 * out.print(returnValue); out.close();
			 */
			request.setAttribute("pageData", pageData);
			// 跳转到通讯录页面
			request.getRequestDispatcher("MTongXunLu.jsp").forward(request, response);

		} else if (op.equals("addreq")) {
			System.out.println("进入请假");
			int fromUserId = 1;
			// 判断如果loginservlet 传过来的session(user)
			if (request.getSession().getAttribute("user") != null) {
				UsersLogin user = (UsersLogin) request.getSession().getAttribute("user");
				// fromUserId=user.getUserId();
				fromUserId = user.getUserId();

			}
			int toUserId = new DepartmentsServiceImp().selDeptManIdByUserId(fromUserId);
			/*
			 * BufferedReader bReader=request.getReader(); StringBuffer sBuffer=new
			 * StringBuffer(); String string=""; while((string = bReader.readLine())!=null)
			 * { sBuffer.append(string); } System.out.println("sb: "+sBuffer); Gson gson=new
			 * Gson(); Requests requests=gson.fromJson(sBuffer+"", Requests.class);
			 */
			String reqContent = request.getParameter("reqContent");
			Requests requests = new Requests();
			requests.setReqContent(reqContent);
			requests.setFromUserId(fromUserId);
			requests.setToUserId(toUserId);
			// Requests req=new Requests(null, fromUserId, toUserId, null, reqContent, 0);
			System.out.println(requests);
			boolean flag = new RequestsServiceImp().addRequests(requests);
			PrintWriter out = response.getWriter();
			out.print(flag);
			out.close();

		} else if (op.equals("")) {
			// 员工登录初始页面
			doQuery(request, response);
		} else if (op.equals("updPwd")) {
			int id = 1;
			if (request.getParameter("id") != null) {
				id = Integer.valueOf(request.getParameter("id"));
			}
			String password = "";
			if (request.getParameter("password") != null) {
				password = request.getParameter("password");
			}
			String newpassword = "";
			if (request.getParameter("newpassword") != null) {
				newpassword = request.getParameter("newpassword");
			}
			System.out.println("id:" + id + " ,原密码：" + password + " ,新密码：" + newpassword);
			boolean flag = userServiceImp.selUserByIdAndPwd(password, id);
			if (flag) {
				boolean flag1 = userServiceImp.updUserPwd(newpassword, id);
				if (flag1) {
					request.setAttribute("value", "修改成功，请重新登录");
					request.getSession().removeAttribute("userMessage");
					request.getSession().removeAttribute("user");
					System.out.println("修改成功");
					response.addHeader("refresh","1");
					
				} else {
					request.setAttribute("value", "因为某些原因修改失败了");
					System.out.println("由于某些原因修改失败了");
				}
			} else {
				request.setAttribute("value", "原密码错误，修改失败");
				System.out.println("原密码错误");
			}
			request.getRequestDispatcher("My_mim.jsp").forward(request, response);

		} else if (op.equals("exit")) {
			request.getSession().setAttribute("user", null);
			// 戴布斯：退出到login.jsp
			request.getRequestDispatcher("login.jsp").forward(request, response);
		} else if (op.equals("tb")) {

			doQuery(request, response);
		}

	}

	private void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int userId = 1;
		int deptId = 1;
		if (request.getSession().getAttribute("user") != null) {
			UsersLogin users = (UsersLogin) request.getSession().getAttribute("user");
			userId = users.getUserId();
			deptId = new DepartmentsServiceImp().selDeptIdByUserId(userId);
		}
		int page = 1;
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.valueOf(request.getParameter("page"));
		}

		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.valueOf(request.getParameter("pageSize"));
		}
		PageData<Attences> pageDataAttence = attencesServiceImp.selAttenceByUserIdByPage(page, pageSize, userId);
		System.out.println(pageDataAttence.getData());

		// 查询员工信息
		List<UserMessage> list = userServiceImp.selUserMessage(userId);
		UserMessage userMessage = list.get(0);
		// 将员工信息传递给页面
		request.getSession().setAttribute("userMessage", userMessage);

		// 查询公司公告
		List<Notices> companyNot = noticesServiceImp.selCompanyNotices();
		// 将公司公告传递给页面
		request.setAttribute("companyNot", companyNot);

		// 查询部门公告
		List<Notices> deptNot = noticesServiceImp.selNoticesByNotLevel(deptId);
		// 将部门公告传递给页面
		request.setAttribute("deptNot", deptNot);

		// 把分页查询到的考勤记录上传
		List<OverTime> overTimeList = attencesServiceImp.selOverTime();

		request.setAttribute("pageDataAttence", pageDataAttence);
		System.out.println("pageDataAttence:" + pageDataAttence.getData());
		request.setAttribute("overTimeList", overTimeList);
		// 今日迟到名单返回值
		LateAndOvertimeUsersService laou = new LateAndOvertimeUsersServiceImp();
		Date date = new Date();
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd ");
		String atttime = ft.format(date) + "00:00:00";
		System.out.println(atttime);
		List<LateAndOvertimeUsers> listlateusers = laou.getLateUsers(atttime, 1);
		// 判断listlateusers是否为空
		if (listlateusers != null) {
			request.setAttribute("listlateusers", listlateusers);
		}

		// 昨日加班名单

		List<OverTime> overTimesUsers = laou.getOvertiomeUsers(atttime, 3);
		System.out.println(overTimesUsers);
		// 判断listlateusers是否为空
		if (overTimesUsers != null) {
			request.setAttribute("overTimesUsers", overTimesUsers);
		}
		AttencesService as = new AttencesServiceImp();
		// 迟到人数
		List<Attences> list1 = as.Weekchidao1();
		// 早退人数
		System.out.println("折线图" + list1);
		List<Attences> list2 = as.Weekzaotui1();
		// 加班人数
		List<Attences> list3 = as.Weekjiaban1();
		// 加班时长
		List<Attences> list4 = as.Weekjiatime1();
		// 正常上班人数
		List<Attences> list5 = as.Weekzhengchang();

		request.setAttribute("list1", list1);
		request.setAttribute("list2", list2);
		request.setAttribute("list3", list3);
		request.setAttribute("list4", list4);
		request.setAttribute("list5", list5);

		request.getRequestDispatcher("MinisterHomePage.jsp").forward(request, response);
		;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
